package org.rain.common.util.json.status;

import org.rain.common.util.json.AbsJsonState;
import org.rain.common.util.json.ContextType;
import org.rain.common.util.json.JsonFsm;

/**
 * created by yangtong on 2025/4/14 22:41:56
 * <br/>
 * 表示期待读取到逗号","或者右括号"}"或者']'
 */
public class ExpectCommaOrEndState extends AbsJsonState {
    @Override
    public void handleNonWhitespace(JsonFsm fsm, char c) {
        handleCommaOrEndState(fsm, c);
    }

    static void handleCommaOrEndState(JsonFsm fsm, char c) {
        //继续读取下一个kv
        if (c == ',') {
            if (fsm.currentEnv() == ContextType.OBJECT) {
                fsm.changeState(EXPECT_KEY);
            } else {
                fsm.changeState(EXPECT_VALUE);
            }
        }
        //表示一个对象或者数组的结束，将当前类型上下文信息弹栈
        else if (c == '}' || c == ']') {
            //弹栈后，如果类型上下文信息长度为0，表示当前对象或者数组就是最外层
            if (fsm.deNesting() == 0) {
                fsm.changeState(END);
            }
        } else {
            throw new RuntimeException("意料之外的字符，期望【,】或【}】或【]】，实际读取到【" + c + "】");
        }
    }
}
